package org.jimmy.tang.thread;

/**
 * @author jimmy
 * 
 */
public class ThreadLocalDemo2 {
    public static void main(String[] args) {
        Thread t1 = new Thread(new Runnable() {
            @Override
            public void run() {
                System.out.println("Thread " + Thread.currentThread().getName()
                        + " has " + SerialNum.get());
            }
        });
        Thread t2 = new Thread(new Runnable() {
            @Override
            public void run() {
                System.out.println("Thread " + Thread.currentThread().getName()
                        + " has " + SerialNum.get());
            }
        });
        t1.start();
        t2.start();
    }

    // 技巧：对threadLocal变量进行简单封装，可以简化多线程操作
    static class SerialNum {
        // The next serial number to be assigned
        private static int nextSerialNum = 0;

        private static ThreadLocal<Integer> serialNum = new ThreadLocal<Integer>() {
            @Override
            protected synchronized Integer initialValue() {
                return new Integer(nextSerialNum++);
            }
        };

        public static int get() {
            return (serialNum.get()).intValue();
        }
    }

}
